import {
  ModalForm,
} from '@ant-design/pro-components';
import { Form, message, } from 'antd';
import { request } from '../../utils/request.ts';
import { useEffect, useState, } from 'react';
import RemoteSelect from '../../components/RemoteSelect/index.jsx';
import { getUserData } from '../../utils/const.ts';

const Edit = ({ open, setOpen, actionRef, record, }) => {
  const [form] = Form.useForm();
  const [level, setLevel] = useState()

  useEffect(() => {
    if (open) {
      const userStr = getUserData();
      const user = JSON.parse(userStr);
      setLevel(user.level);
      const initial = {
        ...record,
        userId: user.level === 2 ? user?.id : undefined,
      };
      form.setFieldsValue(initial);
    }
  }, [open, record, form]);

  return (
    <>
      <ModalForm
        title={record?.id ? "编辑教练证书" : "新增教练证书"}
        form={form}
        autoFocusFirstInput
        open={open}
        width={500}
        layout="horizontal" // 关键点
        labelCol={{ span: 6 }} // label 占 6/24
        wrapperCol={{ span: 18 }} // 输入框占 18/24
        modalProps={{
          destroyOnClose: true,
          onCancel: () => setOpen(false),
        }}
        onFinish={async (values) => {
          const { ...other } = values;
          try {
            const res = await request(record?.id ? '/api/card/update' : '/api/coach/save', {
              method: 'POST',
              data: {
                ...other,
                id: record?.id,
              },
            });
            if (res.data) {
              message.success('提交成功');
              setOpen(false);
              actionRef.current?.reload();
            } else {
              message.error(res.msg);
            }
          } catch (error) {
            console.error('Failed to submit data:', error);
          }
          return true;
        }}
      >
        <RemoteSelect
          name="userId"
          label="教练"
          rules={[{ required: true, message: '请选择教练' }]}
          fetchUrl="/api/user/coach"
          fetchMethod="POST"
          fetchParams={{ status: '-1' }}
          mapOption={item => ({ label: item.name, value: item.id })}
          fieldProps={{
            allowClear: true,
            disabled: level !== 1, // 这里控制禁用
          }}
        />
        <RemoteSelect
          name="cardId"
          label="教练证书"
          rules={[{ required: true, message: '请选择教练证书' }]}
          fetchUrl="/api/card/pageList"
          fetchMethod="POST"
          fetchParams={{ type: '1' }}
          mapOption={item => ({ label: item.name, value: item.id })}
        />
      </ModalForm >
    </>
  );
};
export default Edit;
